﻿'use strict';

angular.module('ishaCrmApp')

    .factory('stateSvc', ['$rootScope', '$cookieStore', 'googleAuthSvc', function ($rootScope, $cookieStore, googleAuthSvc) {

        var stateSvcObject = {};

        stateSvcObject.alertMessages = [];

        stateSvcObject.alerAddUniqueMessage = function(newMessageToAdd) {
            this.alertMessages = $.grep(this.alertMessages, function (message) { return message.message != newMessageToAdd.message; });
            this.alertMessages.push(newMessageToAdd);
            $rootScope.$emit('EVENT:ALERTS-ADDED', this.alertMessages);
        }

        stateSvcObject.alertError = function (msg) {
            this.alerAddUniqueMessage({ message: msg, type: 'alert-danger', msgPrefix: 'Error!' });
        }
        stateSvcObject.alertSuccess = function (msg) {
            this.alerAddUniqueMessage({ message: msg, type: 'alert-success', msgPrefix: 'Success!' });
        }
        stateSvcObject.alertInfo = function (msg) {
            this.alerAddUniqueMessage({ message: msg, type: 'alert-info', msgPrefix: 'Information!' });
        }
        stateSvcObject.alertWarning = function (msg) {
            this.alerAddUniqueMessage({ message: msg, type: 'alert-warning', msgPrefix: 'Warning!' });
        }

        stateSvcObject.alertRemove = function (messageToRemove) {
            this.alertMessages = $.grep(this.alertMessages, function (message) { return message != messageToRemove; });
            $rootScope.$emit('EVENT:ALERTS-REMOVED', this.alertMessages);
        }



        // Menu state Interface
        stateSvcObject.activeMenu = 'Home';
        stateSvcObject.setActiveMenu = function (menu) {
            this.activeMenu = menu;
            $rootScope.$emit('EVENT:MENU.CHANGED', menu);
        }

        stateSvcObject.authenticated = false;
        //stateSvcObject.authorised = false;
        stateSvcObject.lastError = '';

        // User Auth info interface
        stateSvcObject.authUserInfo = null;
        stateSvcObject.setAuthInfo = function (authInfo) {
            this.authUserInfo = authInfo;
            this.authenticated = this.isAuthenticated();
            //this.authorised = this.isAuthorised();
            if (this.isAuthenticated()) {
                $cookieStore.put(app.CLIENT_ID, app.CookieValue);
            }
            $rootScope.$emit('EVENT:AUTH.LOGGEDIN');
        }

        stateSvcObject.loginUserEmail = function () {
            var email = $.trim(this.authUserInfo && this.authUserInfo.email ? this.authUserInfo.email : '');
            return email.toLowerCase();
        },

        stateSvcObject.loginUserFullname = function () {
            return $.trim((this.authUserInfo && this.authUserInfo.given_name ? this.authUserInfo.given_name : '') + ' ' + (this.authUserInfo && this.authUserInfo.family_name ? this.authUserInfo.family_name : ''));
        }

        stateSvcObject.isAuthenticated = function () {
            var email = this.loginUserEmail();
            return (email != '');
        };

        stateSvcObject.isAuthorised = function () {

            var _this = this;
            var email = this.loginUserEmail();

            // Get List of users
            gapi.client.user.userApi.getAll().execute(function (resp) {
                if (resp && resp.statusCode) {
                    if (resp.statusCode === "SUCCESS") {
                        angular.forEach(resp.object, function (value, key) {
                            if (value.email.toLowerCase() == email) {
                                return true;
                            }
                        });
                    } else {
                        _this.lastError = (resp && resp.userFriendlyMessage ? resp.userFriendlyMessage : this.lastError);
                        return false;
                    }
                }
            });
        }

        stateSvcObject.login = function () {

            var _this = this;

            googleAuthSvc.login().then(function (profileData) {
                if (profileData && profileData.email) {
                    _this.setAuthInfo(profileData);
                } else {
                    _this.lastError = 'ERROR-FETCHING-USER-PROFILE-DATA';
                }
            }, function (err) {
                _this.lastError = (err ? err : this.lastError);
                _this.setAuthInfo(null);
            });

        }

        stateSvcObject.signIn = function () {

            var _this = this;

            googleAuthSvc.checkLogin().then(function (profileData) {
                if (profileData && profileData.email) {
                    _this.setAuthInfo(profileData);
                }
            }, function (err) {
                _this.lastError = (err ? err : this.lastError);
                _this.setAuthInfo(null);
            });
        },

        stateSvcObject.signOut = function () {
            this.setAuthInfo(null);
            this.authenticated = false;
            gapi.auth.setToken(null);
            $cookieStore.remove(app.CLIENT_ID);
        }

        return stateSvcObject;

    }]);